<template>
  <div class="news-manage">
    <div class="page-header">
      <h2>新闻管理</h2>
      <button class="add-btn" @click="showAddDialog">添加新闻</button>
    </div>
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入新闻标题或内容"
        class="search-input"
        @keyup.enter="searchNews"
      >
        <template #append>
          <el-button @click="searchNews">搜索</el-button>
        </template>
      </el-input>
    </div>
    <!-- 新闻列表 -->
    <div class="news-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>标题</th>
            <th>作者</th>
            <th>发布时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="news in paginatedNewsList" :key="news.id">
            <td>{{ news.id }}</td>
            <td>{{ news.title }}</td>
            <td>{{ news.author }}</td>
            <td>{{ $formatDate(news.createDate) }}</td>
            <td>
              <span
                :class="['status', news.isPublish === 1 ? 'published' : 'draft']"
              >
                {{ news.isPublish === 1 ? "已发布" : "草稿" }}
              </span>
            </td>
            <td>
              <button class="edit-btn" @click="handleEdit(news)">编辑</button>
              <button class="delete-btn" @click="handleDelete(news.id)">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <div class="dialog" v-if="showDialog" @click.self="closeDialog">
      <div class="dialog-content">
        <h3>{{ isEdit ? "编辑新闻" : "添加新闻" }}</h3>
        <div class="form-group">
          <label>标题：</label>
          <input
            type="text"
            v-model="currentNews.title"
            placeholder="请输入新闻标题"
          />
        </div>
        <div class="form-group">
          <label>作者：</label>
          <input
            type="text"
            v-model="currentNews.author"
            placeholder="请输入作者"
          />
        </div>
        <div class="form-group">
          <label>内容：</label>
          <textarea
            v-model="currentNews.content"
            placeholder="请输入新闻内容"
          ></textarea>
        </div>
        <div class="form-group">
          <label>状态：</label>
          <select v-model="currentNews.status">
            <option value="0">草稿</option>
            <option value="1">发布</option>
          </select>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="handleSave">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed , getCurrentInstance} from "vue";
import axios from "axios";
import { ElPagination } from "element-plus";

const { proxy } = getCurrentInstance();
const searchQuery = ref("");
const newsList = ref([]);
const showDialog = ref(false);
const isEdit = ref(false);
const currentNews = ref({
  id: null,
  title: "",
  author: "",
  content: "",
  isPublish: "0",
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取新闻列表
const fetchNewsList = async () => {
  try {
    const response = await axios.get('/api/news/list', {
      params: {
        pageNo: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (response.data.code === 200) {
      newsList.value = response.data.data.list;
      total.value = response.data.data.total;
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error);
  }
};

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchNewsList();
};

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchNewsList();
};

// 搜索新闻
const searchNews = async () => {
  try {
    const response = await axios.get('/api/news/searchNews', {
      params: {
        keyword: searchQuery.value,
        categoryId: '',
        pageNo: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (response.data.code === 200) {
      newsList.value = response.data.data.list;
      total.value = response.data.data.total;
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error);
  }
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false;
  currentNews.value = {
    id: null,
    title: "",
    author: "",
    content: "",
    isPublish: "0",
  };
  showDialog.value = true;
};

// 显示编辑对话框
const handleEdit = (news) => {
  isEdit.value = true;
  currentNews.value = { ...news };
  showDialog.value = true;
};

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false;
  currentNews.value = {
    id: null,
    title: "",
    author: "",
    content: "",
    status: "0",
  };
};

// 保存新闻
const handleSave = async () => {
  try {
    const url = isEdit.value ? `/api/news/update` : `/api/news/add`;
    const response = await axios[isEdit.value ? "put" : "post"](
      url,
      currentNews.value
    );
    if (response.data.code === 200) {
      alert(isEdit.value ? "更新成功" : "添加成功");
      closeDialog();
      fetchNewsList();
    }
  } catch (error) {
    alert("操作失败");
    console.error("保存新闻失败:", error);
  }
};

// 删除新闻
const handleDelete = async (id) => {
  if (!confirm("确定要删除这条新闻吗？")) return;
  try {
    const response = await axios.delete(`/api/news/delete/${id}`);
    if (response.data.code === 200) {
      alert("删除成功");
      fetchNewsList();
    }
  } catch (error) {
    alert("删除失败");
    console.error("删除新闻失败:", error);
  }
};

// 删除本地分页计算
const paginatedNewsList = computed(() => newsList.value);

onMounted(() => {
  fetchNewsList();
});
</script>

<style scoped>
.news-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.add-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.news-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e8e8e8;
}

th {
  background-color: #fafafa;
  font-weight: 500;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.published {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.draft {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #d3d4d6;
}

.edit-btn,
.delete-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  margin-right: 8px;
  cursor: pointer;
}

.edit-btn {
  background-color: #1890ff;
  color: white;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 500px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-group textarea {
  width: 100%;
  height: 120px;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: vertical;
}

.dialog-footer {
  margin-top: 24px;
  text-align: right;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  margin-left: 8px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f4f4f5;
  color: #606266;
}

.confirm-btn {
  background-color: #1890ff;
  color: white;
}

.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}
.search-bar {
  width: 350px;
  margin-bottom: 20px;
}
</style>
